<?php
/**
 * Created by PhpStorm.
 * User: songyichao
 * Date: 2017/9/19
 * Time: 10:50
 */

namespace backend\models;

use yii\base\Model;
use yii\bootstrap\Html;
use yii\helpers\ArrayHelper;

class ExcelModel extends Model
{
    /**
     * 会员列表导出
     * @param $query
     */
    public static function userExport($query)
    {
        error_reporting(0);
        $data = [];
        $area = new AreaModel();
        $query->select('id,nickname,telephone,province,city,country,status,is_delete,create_time');
        foreach($query->each(10000) as $key => $item){
            $data[] = [
                $item->id,
                $item->nickname,
                $item->telephone,
                implode(' ',$area->getAreaName([$item->province,$item->city,$item->country])),
                $item->statusName,
                $item->formatDateTime,
            ];
        }
        self::csv_export($data,['ID','昵称','手机号','地区','状态','注册时间'],date('YmdHis').'会员列表导出');
    }
    /**
     * 课程列表导出
     * @param $query
     */
    public static function courseExport($query)
    {
        error_reporting(0);
        $data = [];
        $class_cache_arr=[];
        $query->select('id,name,teacher_id,organization_id,class_id,price,is_delete,is_checked,create_time,sourse')
        ->with(['user'=>function($m){
            return $m->select('id,nickname');
        },'courseVideo'=>function($m){
            return $m->select('course_id,count(0) as video_count')->groupBy('course_id');
        }]);
        foreach($query->each(1000) as $key => $item){
            //缓存class列表
            if(isset($class_cache_arr[$item->class_id])){
                $class_name = $class_cache_arr[$item->class_id];
            }else{
                $class_name = implode(' > ',ArrayHelper::getColumn($item->classBreadcrumbs($item->class_id),'name'));
                $class_cache_arr[$item->class_id] = $class_name;
            }
            $data[] = [
                $item->id,
                $item->name,
                !empty($item->organization) ? '机构': '老师',
                !empty($item->organization) ? $item->organization->name: !empty($item->user)?$item->user->nickname:'',
                $class_name,
                $item->price>0?$item->price.'元':'免费',
                isset($item->courseVideo[0]) ? $item->courseVideo[0]["video_count"] : 0,
                $item->statusName,
                $item->sourseName,
                $item->formatDateTime,
            ];
        }
        self::csv_export($data,['ID','名称','身份','昵称/机构名','类别','起价','视频数','状态','来源','创建时间'],date('YmdHis').'课程列表导出');
    }
    /**
     * 视频列表导出
     * @param $query
     */
    public static function videoExport($query)
    {
        error_reporting(0);
        $data = [];
        $query->select('id,teacher_id,course_id,title,price,month_price,year_price,duration,size,sale_count,play_count,is_delete,is_checked,status_shelves,create_time')
        ->with(['course'=>function($m){
           return $m->select('id,name');
        },'user'=>function($m){
           return $m->select('id,nickname');
        }]);
        foreach($query->each(1000) as $key => $item){
            $data[] = [
                $item->id,
                $item->title,
                empty($item->course) ? '': $item->course->name,
                !empty($item->organization) ? $item->organization->name: !empty($item->user)?$item->user->nickname:'',
                $item->price.' / '.$item->month_price.' / '.$item->year_price,
                $item::secToTime($item->duration),
                $item::formatBytes($item->size),
                $item->sale_count,
                $item->play_count,
                $item->statusName,
                date('Y-m-d H:i',$item->create_time),
            ];
        }
        self::csv_export($data,['ID','视频标题','课程名称','老师姓名','价格天/月/年','时长','大小','销售数','播放次数','状态','添加时间'],date('YmdHis').'视频列表导出');
    }
    /**
     * 分润代理商导出
     * @param $query
     */
    public static function ordersIncomeAgentExport($query)
    {
        error_reporting(0);
        $data = [];
        foreach($query->each(10000) as $key => $item){
            $data[] = [
                $item->orders_id,
                !empty($item->orders) ? $item->orders->amount_paid:0,
                (double)$item->agent_amount_student_in_area,
                (empty($item->agentStudent->name)?'':Html::encode($item->agentStudent->name).' / '.$item->agent_id_student_in_area),
                (double)$item->agent_amount_teacher_in_area,
                (empty($item->agentTeacher->name)?'':Html::encode($item->agentTeacher->name).' / '.$item->agent_id_teacher_in_area),
                date('Y-m-d H:i',$item->create_time),
            ];
        }
        self::csv_export($data,['订单ID','订单金额','学生区域代理商('.(\Yii::$app->params['orders_income_rate']['agent_amount_student']*100).'%)','代理商名称/ID','老师区域代理商('.(\Yii::$app->params['orders_income_rate']['agent_amount_teacher']*100).'%)','代理商名称/ID','时间'],date('YmdHis').'代理商收益导出');
    }

    /**
     * 分润老师导出
     * @param $query
     */
    public static function ordersIncomeTeacherExport($query)
    {
        error_reporting(0);
        $data = [];
        foreach($query->each(10000) as $key => $item){
            $data[] = [
                $item->orders_id,
                !empty($item->orders) ? $item->orders->amount_paid:0,
                $item->teacher_id?(double)$item->teacher_amount:($item->organization_id?(double)$item->organization_amount:0),
                $item->teacher_id?(empty($item->teacherUser->nickname)?'':Html::encode($item->teacherUser->nickname)):(empty($item->organization->name)?'':Html::encode($item->organization->name)),
                $item->teacher_id?$item->teacher_id:$item->organization_id,
                date('Y-m-d H:i',$item->create_time),
            ];
        }
        self::csv_export($data,['订单ID','订单金额','收益('.(\Yii::$app->params['orders_income_rate']['teacher_amount']*100).'%)','老师/机构名称','老师/机构ID','时间'],date('YmdHis').'老师/机构收益导出');
    }

    /**
     * 分润平台导出
     * @param $query
     */
    public static function ordersIncomePlatformExport($query)
    {
        error_reporting(0);
        $data = [];
        foreach($query->each(10000) as $key => $item){
            $data[] = [
                $item->orders_id,
                !empty($item->orders) ? $item->orders->amount_paid:0,
                (double)$item->platform_amount,
                date('Y-m-d H:i',$item->create_time),
            ];
        }
        self::csv_export($data,['订单ID','订单金额','收益(≥'.(\Yii::$app->params['orders_income_rate']['platform_amount']*100).'%)','时间'],date('YmdHis').'平台收益导出');
    }
    /*
     * 暑假包购买导出
     * @param $query
     */
    public static function summerVacationOrderExport($query)
    {
        error_reporting(0);
        $data = [];
        foreach($query->each(10000) as $key => $item){
            $data[] = [
                $item->order_code,
                $item->user_id,
                $item->userName,
                !empty($item->user->agentArea->agent)?$item->user->agentArea->agent->name:'',
                !empty($item->user->agentArea->agent)?$item->user->agentArea->agent->id:'',
                $item->resetTelephone,
                $item->redeem_code,
                $item->saleInfo,
                $item->payClass,
                $item->price,
                $item->sourceType,
                $item->channelName,
                $item->payType,
                $item->payTime,
            ];
        }
        self::csv_export($data,['订单号','购买者id','用户昵称','代理商名称','代理商ID','电话号码','兑换码','购买详情','支付方式','支付价格','来源','渠道','状态','购买时间'],date('YmdHis').'暑假包购买导出');
    }
    /*
     * 暑假包转盘中奖导出
     * @param $query
     */
    public static function summerVacationUserPrizeExport($query)
    {
        error_reporting(0);
        $data = [];
        foreach($query->each(10000) as $key => $item){
            $data[] = [
                $item->user_id,
                $item->user->nickname,
                $item->formatTelephone,
                $item->desc,
                empty($item->userCoupon) ? '' : ($item->userCoupon->is_use == 1?'未使用':'已使用'),
                $item->list_show == 1?'是':'否',
                $item->sort,
                $item->formatDateTime,
            ];
        }
        self::csv_export($data,['用户ID','用户昵称','手机号','获取奖励','状态','列表显示','列表顺序','时间'],date('YmdHis').'暑假包转盘中奖导出');
    }
    /*
     * 暑假包邀请中奖管理导出
     * @param $query
     */
    public static function summerVacationUserCashExport($query)
    {
        error_reporting(0);
        $data = [];
        foreach($query->each(10000) as $key => $item){
            $data[] = [
                $item->user_id,
                $item->user->nickname,
                $item->user->resetTelephone,
                $item->sub_user_id,
                $item->subUser->resetTelephone,
                $item->price,
                !empty($item->userAccount)?$item->userAccount->name:'',
                !empty($item->userAccount)?$item->userAccount->username:'',
                $item->price,
                $item->formatDateTime,
                isset(ActiviteUserCashModel::$status_arr[$item->status])?ActiviteUserCashModel::$status_arr[$item->status]:'',
            ];
        }
        self::csv_export($data,['用户ID','用户昵称','手机号','被邀请人ID','被邀请人手机号','获取奖励金额','收款姓名','收款账户','时间','状态'],date('YmdHis').'暑假包邀请中奖管理导出');
    }
    /*
     * 暑假包兑换码导出
     * @param $query
     */
    public static function summerVacationRedeemCodeExport($query)
    {
        error_reporting(0);
        $data = [];
        foreach($query->each(10000) as $key => $item){
            $data[] = [
                $item->id,
                $item->redeem_code,
                $item->useTypeName,
                $item->typeName,
                $item->priceName,
                $item->useStatus,
            ];
        }
        self::csv_export($data,['ID','兑换码','活动名称','类型','券价值','使用状态'],date('YmdHis').'暑假包兑换码导出');
    }
    /*
     * 提现审核列表
     * @param $query
     */
    public static function withdrawApplyList($query,$is_checked)
    {
        error_reporting(0);
        $data = [];
        foreach($query->each(10000) as $key => $val){
            if(strlen($val->receive_mobie) >= 3 && $is_checked != 1 && !in_array(\Yii::$app->user->id, \Yii::$app->params['user'])){
                $val->receive_mobie = substr($val->receive_mobie,0,3).'***';
            }
            $is_checked_name = $val->statusName;
            if($val->class == 1){
                if(!$val->agent || $val->agent->is_delete != 0 || $val->agent->status != 0){
                    $is_checked_name = '代理商异常';
                }
            }else if($val->class == 0){
                if(!$val->user || $val->user->is_delete != 0 || $val->user->status != 0 || $val->user->class != 1 || !$val->teacher || $val->teacher->is_checked != 1){
                    $is_checked_name = '老师异常';
                }
            }else if($val->class == 2){
                if(!$val->user || $val->user->is_delete != 0 || $val->user->status != 0 || !$val->organization || $val->organization->is_checked != 1){
                    $is_checked_name = '机构异常';
                }
            }
            $data[] = [
                $val->id,
                $val->className,
                $val->nickname,
                $val->belong_id,
                $val->receive_account,
                $val->receive_mobie,
                $val->amountIncome,
                $val->amount,
                $is_checked_name,
                date('Y-m-d H:i',$val->create_time)
            ];
        }
        self::csv_export($data,['ID','身份','昵称','用户ID','支付宝姓名','支付宝账户','当前余额','提现金额','状态','申请时间'],date('YmdHis').'提现审核列表导出');
    }
    /*
     * 提现记录列表
     * @param $query
     */
    public static function withdrawRecordList($query)
    {
        error_reporting(0);
        $data = [];
        foreach($query->each(10000) as $key => $val){
            if(strlen($val->receive_mobie) >= 3){
                $val->receive_mobie = substr($val->receive_mobie,0,3).'***';
            }
            $data[] = [
                $val->id,
                $val->className,
                $val->nickname,
                $val->belong_id,
                $val->receive_account,
                $val->receive_mobie,
                $val->amount,
                date('Y-m-d H:i',$val->create_time)
            ];
        }
        self::csv_export($data,['ID','身份','昵称','用户ID','支付宝姓名','支付宝账户','提现金额','申请时间'],date('YmdHis').'提现记录列表导出');
    }
    /*
     * 充值列表
     * @param $query
     */
    public static function rechargeList($query)
    {
        error_reporting(0);
        $data = [];
        foreach($query->each(10000) as $key => $val){
            $data[] = [
                $val->id,
                $val->user->nickname,
                isset(RechargeModel::$class_name[$val->class])?RechargeModel::$class_name[$val->class]:'',
                $val->amount_paid,
                date('Y-m-d H:i',$val->create_time)
            ];
        }
        self::csv_export($data,['ID','昵称','用户ID','充值方式','充值金额','支付时间'],date('YmdHis').'充值列表导出');
    }

    /**
     * 导出excel(csv)
     * @data 导出数据
     * @headlist 第一行,列名
     * @fileName 输出Excel文件名
     */
    public static function csv_export(&$data, $headlist = array(), $fileName) {

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$fileName.'.csv"');
        header('Cache-Control: max-age=0');

        //打开PHP文件句柄,php://output 表示直接输出到浏览器
        $fp = fopen('php://output', 'a');

        //输出Excel列名信息
        foreach ($headlist as $key => $value) {
            //CSV的Excel支持GBK编码，一定要转换，否则乱码
            $headlist[$key] = iconv('utf-8', 'gbk', $value);
        }

        //将数据通过fputcsv写到文件句柄
        fputcsv($fp, $headlist);

        //计数器
        $num = 0;

        //每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
        $limit = 100000;

        //逐行取出数据，不浪费内存
        $count = count($data);
        for ($i = 0; $i < $count; $i++) {

            $num++;

            //刷新一下输出buffer，防止由于数据过多造成问题
            if ($limit == $num) {
                ob_flush();
                flush();
                $num = 0;
            }

            $row = $data[$i];
            foreach ($row as $key => $value) {
                $value = is_numeric($value) ? $value."\t" : $value;
                $row[$key] = iconv('utf-8', 'gbk//IGNORE', ($value));
            }

            fputcsv($fp, $row);
        }
        exit;
    }
}